package com.traitswu.simple.demo.controller;

import com.traitswu.simple.demo.exception.FileUpdownException;
import com.traitswu.simple.demo.service.FileUpdownService;
import com.traitswu.simple.demo.store.FileDesc;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;


@RestController
public class FileUpdownController {

    @Resource
    private FileUpdownService fileUpdownService;


    @RequestMapping(value = "/doUpload", method = RequestMethod.POST,
            consumes = {"multipart/form-data"})
    public FileDesc upload(@RequestParam MultipartFile file, @RequestParam String path) {
        try {
            return fileUpdownService.uploadBeforeConfirm(file.getInputStream(), path);
        } catch (Exception e) {
            throw new FileUpdownException(e.getMessage());
        }
    }


    @PostMapping("/upload/confirm")
    public void uploadConfirm(@RequestBody FileDesc desc) {

        try {
            fileUpdownService.uploadAfterConfirmed(desc);
        } catch (IOException e) {
            throw new FileUpdownException(e.getMessage());
        }
    }


    @GetMapping("/download")
    public ResponseEntity<InputStreamResource> download(@RequestParam String filePath) {

        try {

            File file = new File(filePath);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            InputStream inputStream = fileUpdownService.download(filePath);
            return ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new InputStreamResource(inputStream));
        } catch (IOException e) {
            throw new FileUpdownException(e.getMessage());
        }

    }


}
